package manager;


import interfaz.ManagerArticuloIf;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import domain.Articulo;
import dto.ArticuloDTO;
import exceptions.ExceptionArticulo;

@Stateless
public class ManagerArticulo   implements ManagerArticuloIf{
	private static Logger logger = Logger.getLogger(ManagerArticulo.class);
	
	@PersistenceContext(unitName="tpoai")
    EntityManager em;

	public ManagerArticulo() throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void despachar() throws ExceptionArticulo, RemoteException {
		//PROCESAMIENTO
		
	}
	
	public ArticuloDTO getArticulo(String codigo)throws ExceptionArticulo, RemoteException {
	
		List<Articulo> a1 = (List<Articulo>) em.createQuery("select distinct c from Articulo c where c.codigo = :codigo").setParameter("codigo", codigo).getResultList();
		Articulo a=null;
		if(a1!=null){
			a= a1.get(0);
		}
			
		
		if (a!=null) {
			logger.info("Obteniendo articulo de la DB:"+ a.getDescripcion());
			return a.getVista();
		}
		return null;
	}
	
	@Override
	public List<ArticuloDTO> getArticulos(String word,String filtro)	throws ExceptionArticulo, RemoteException {
		@SuppressWarnings("rawtypes")
		
		Iterator q = null;
		
		if(filtro==null || word == null)
			q = em.createQuery("select c from Articulo c").getResultList().iterator();
		else if(filtro.isEmpty() || word.isEmpty())
			q = em.createQuery("select c from Articulo c").getResultList().iterator();
		else if(filtro.equals("deposito"))
			q = em.createQuery("select c from Articulo c where c.deposito LIKE :word").setParameter("word", word).getResultList().iterator();
		else if(filtro.equals("descripcion"))
			q = em.createQuery("select c from Articulo c where c.descripcion LIKE :word").setParameter("word", word).getResultList().iterator();
		else if(filtro.equals("codigo"))
			q = em.createQuery("select c from Articulo c where c.codigo LIKE :word").setParameter("word", word).getResultList().iterator();
		
		//q = em.createQuery("select c from Articulo c").getResultList().iterator();
		List<ArticuloDTO> arts=new ArrayList<ArticuloDTO>();
		
		  while(q.hasNext())
		  {
		    Articulo c = (Articulo)q.next();
		    arts.add(c.getVista());
			logger.info("Obteniendo articulo de la DB:"+ c.getDescripcion());

		  }
		  return arts;
	}



	@Override
	public void save(ArticuloDTO a) throws ExceptionArticulo, RemoteException {
		Articulo u=new Articulo();
		u.setCodigo(a.getCodigo());
		u.setDeposito(a.getDeposito());
		u.setDescripcion(a.getDescripcion());
		em.merge(u);
		em.flush();

	}



}
